package me.nibo.webframework.service.account;

import me.nibo.webframework.commons.enumeration.Status;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * 登录认证类，用于 apache shiro 在执行认证（登录）时，通过该类对登录信息认证（登录）是否通过
 * Created by nibo on 2015/7/30.
 */

public class JdbcAuthenticationRealm extends AuthorizationRealm {

    @Autowired
    private AccountService accountService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        String username = usernamePasswordToken.getUsername();
        Map<String, Object> user = accountService.getUserByUserName(username);
        if (MapUtils.isEmpty(user)) {
            throw new IncorrectCredentialsException("用户名或密码不正确");
        }
        if (Status.DISABLE.getValue().equals(user.get("status"))) {
            throw new DisabledAccountException(username + " 账号已被禁用");
        }

        return new SimpleAuthenticationInfo(user,
                user.get("password"), ByteSource.Util.bytes(user.get("username")), getName());
    }
}
